package com.manner.groupon.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@Slf4j
public class RequestUtil {

    private static ServletRequestAttributes servletRequestAttributes;

    private static HttpServletRequest request;

    private static HttpServletResponse response;


    static {
        //获取请求信息
        servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //获取请求
        request = servletRequestAttributes.getRequest();
        //获取响应
        response = servletRequestAttributes.getResponse();
    }

    /**
     * 设置响应头
     *
     * @param key 数据键
     * @param val 数据值
     */
    public static void setResponseHeader(String key, String val) {
        //设置响应头
        response.setHeader(key, val);
    }

    /**
     * 获取请求前置
     *
     * @return
     */
    public static String getRequestURI() {
        //获取请求协议
        String schema = request.getScheme();
        //获取请求IP
        String ip = request.getServerName();
        //获取请求端口
        int port = request.getServerPort();
        //拼接返回
        return schema + "://" + ip + ":" + port;
    }


    /**
     * 获取请求体
     *
     * @param request
     * @return
     * @throws IOException
     */
    public static String getRequestBody(HttpServletRequest request) {
        ServletInputStream stream = null;
        BufferedReader reader = null;
        StringBuffer sb = new StringBuffer();
        try {
            stream = request.getInputStream();
            // 获取响应
            reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            log.error("读取返回支付接口数据流出现异常");
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                log.error("关闭异常");
            }
        }
        return sb.toString();
    }

}
